package blocks {
	import flash.geom.Rectangle;
	import org.flixel.*;
	
	
	/**
	 * This allows you to define per-tile animations for a tilemap.
	 * These are done via a FlxSprite instance so that you can manipulate
	 * it as much as you like.
	 */
	
	public class AnimatedTilemap extends FlxTilemap {
		public var sprites:Array;
		protected var lastFrames:Array;
		protected var tileRect:Rectangle;
		
		
		public function AnimatedTilemap() {
			super();
			tileRect = new Rectangle();
			tileRect.x = 0;
			tileRect.y = 0;
		}
		
		
		override public function loadMap(MapData:String, TileGraphic:Class, TileWidth:uint=0, TileHeight:uint=0, AutoTile:uint=OFF, StartingIndex:uint=0, DrawIndex:uint=1, CollideIndex:uint=1):FlxTilemap {
			super.loadMap(MapData, TileGraphic, TileWidth, TileHeight, AutoTile, StartingIndex, DrawIndex, CollideIndex);
			sprites = [];
			lastFrames = [];
			tileRect.width = _tileWidth;
			tileRect.height = _tileHeight;
			return this;
		}
		
		
		override public function update():void {
			for (var i:int = 0; i < sprites.length; i++)
				if (sprites[i] is FlxSprite)
					(sprites[i] as FlxSprite).update();
			
			super.update();
		}
		
		
		override public function draw():void {
			_flashPoint.y = 0;
			
			for (var i:int = 0; i < sprites.length; i++)
				if (sprites[i] is FlxSprite) {
					var sprite:FlxSprite = sprites[i] as FlxSprite;
					
					// if the sprite's frame changed, paint it onto our pixels
					if (sprite.frame != lastFrames[i] || true) {
						_flashPoint.x = i * _tileWidth;
						if (_flashPoint.x >= _tiles.width) {
							_flashPoint.y = uint(_flashPoint.x / _tiles.width) * _tileHeight;
							_flashPoint.x %= _tiles.width;
						}
						
						_tiles.copyPixels(sprite.framePixels, tileRect, _flashPoint);
						lastFrames[i] = sprite.frame;
					}
				}
			
			super.draw();
		}
	}
}
